package cn.com.gzheroli.core.common.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.persistence.Column;
import javax.persistence.Transient;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.SQL;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.dozer.DozerBeanMapper;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageHelper;

import cn.com.gzheroli.bfw.pojo.base.DuplicateCheckPage;
import cn.com.gzheroli.bfw.pojo.base.TSDepart;
import cn.com.gzheroli.bfw.pojo.base.TSFunction;
import cn.com.gzheroli.bfw.pojo.base.TSType;
import cn.com.gzheroli.bfw.pojo.base.TSTypegroup;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.entity.TableAndColumns;
import cn.com.gzheroli.core.common.mapper.CommonMapper;
import cn.com.gzheroli.core.common.mapper.DictGroupTypeMapper;
import cn.com.gzheroli.core.common.mapper.RoleMapper;
import cn.com.gzheroli.core.common.mapper.UserMapper;
import cn.com.gzheroli.core.common.model.common.UploadFile;
import cn.com.gzheroli.core.common.model.json.ImportFile;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.common.service.impl.CommonServiceImpl;
import cn.com.gzheroli.core.util.DataUtils;
import cn.com.gzheroli.core.util.NameHandler;
import cn.com.gzheroli.core.util.NameUtils;
import cn.com.gzheroli.core.util.FileUtils;
import cn.com.gzheroli.core.util.GenericsUtils;
import cn.com.gzheroli.core.util.PinyinUtil;
import cn.com.gzheroli.core.util.ReflectHelper;
import cn.com.gzheroli.core.util.ResourceUtil;
import cn.com.gzheroli.core.util.StreamUtils;
import cn.com.gzheroli.core.util.StringUtil;
import cn.com.gzheroli.core.util.oConvertUtils;
import cn.com.gzheroli.core.util.mybatis.SqlMapper;
import cn.com.gzheroli.util.TagUtil;
/**
 * 
* @类名: SystemServiceImpl  
* @描述: TODO(这里用一句话描述这个类的作用)  
* @作者: 李长荣 lichang_20011@163.com  
* @日期: 2017年10月22日  上午8:59:46
*@version V1.0  
*
 */
@Service("systemService")
public class SystemServiceImpl implements SystemService {
	private static final Logger logger = Logger.getLogger(SystemServiceImpl.class);
	@Autowired
	private SpringRedisCache cache;
	@Resource
	private DictGroupTypeMapper dictGroupTypeMapper;
	@Resource
	private RoleMapper roleMapper;
	@Resource
	private CommonMapper commonMapper;
	// SQL 使用JdbcDao

	@Autowired
	private CommonService commonService;

	@Resource
	SqlSessionTemplate sqlSessionTemplate;

	@Resource
	private UserMapper userMapper;
	@Autowired
	SqlMapper sqlMapper;

	/**
	 * 根据类型编码和类型名称获取Type,如果为空则创建一个
	 * 
	 * @param typeCode
	 * @param typeName
	 * @return
	 */
	@Override
	public TSType getType(String typeCode, String typeName, String typeGroupId) {
		TSType actType = (TSType) commonService.findUniqueByProperty(TSType.class, "typeCode", typeCode);
		if (actType == null) {
			actType = new TSType();
			actType.setTypeCode(typeCode);
			actType.setTypeGroupId(typeGroupId);
			actType.setTypeName(typeName);
			commonService.save(actType);
		}
		return actType;

	}

	/**
	 * 根据类型分组编码和名称获取TypeGroup,如果为空则创建一个
	 * 
	 * @param typecode
	 * @param typename
	 * @return
	 */
	@Override
	public TSTypegroup getTypeGroup(String typeGroupCode, String typeGroupName) {
		TSTypegroup tsTypegroup = (TSTypegroup) commonService.findUniqueByProperty(TSTypegroup.class, "typeGroupCode",
				typeGroupCode);
		if (tsTypegroup == null) {
			tsTypegroup = new TSTypegroup();
			tsTypegroup.setTypeGroupCode(typeGroupCode);
			tsTypegroup.setTypeGroupName(typeGroupName);
			commonService.save(tsTypegroup);
		}
		return tsTypegroup;
	}
	@Override
	public TSTypegroup getTypeGroupByCode(String typegroupCode) {
		TSTypegroup tsTypegroup = (TSTypegroup) commonService.findUniqueByProperty(TSTypegroup.class, "typeGroupCode",
				typegroupCode);
		return tsTypegroup;
	}


	/**
	 * 
	 * @Title: getAllTables @Description: 加载所有表名到缓存 @param @param tableName
	 * 设定文件 @return void 返回类型 @throws
	 */
	@Override
	public List<String> getAllTables(String tableName) {
		System.out.println("执行SystemServiceImpl: initTables构造方法");
		String dataBaseType = sqlSessionTemplate.getConfiguration().getDatabaseId();
		Map para = new HashMap();
		String schemaName = commonMapper.getDatabaseName();
		para.put("schemaName", schemaName);
		cache.putCache("schemaName", schemaName);
		List<String> allTables = cache.getCache("allUserTable", List.class);
		if (tableName != null && !tableName.trim().equals("")) {

			if (!allTables.contains(tableName)) {
				allTables = commonMapper.getAllTables(para);
				cache.deleteCache("allUserTable");
				cache.putCache("allUserTable", allTables);
			}
		} else {
			allTables = commonMapper.getAllTables(para);
			cache.deleteCache("allUserTable");
			cache.putCache("allUserTable", allTables);

		}
		return allTables;
	}
	public void getInitAllTables(String tableName) {
		if(tableName==null||tableName.trim().equals(""))
			return;
		System.out.println("执行SystemServiceImpl: initAllTables构造方法");  
		String dataBaseType=sqlSessionTemplate.getConfiguration().getDatabaseId();
		Map para=new HashMap();
		String schemaName=commonMapper.getDatabaseName();
		para.put("schemaName", schemaName);
		cache.putCache("schemaName", schemaName);
		//删除缓存中的表字段
		HashMap<String, Map<String,Object>> userTableMap = cache.getCache("heroTable", HashMap.class);
		if(null!=userTableMap&&!userTableMap.isEmpty()) {
		userTableMap.remove(tableName);
		cache.putCache("heroTable", userTableMap);
		}
		List<String> allTables = cache.getCache("allUserTable", List.class);
		if(allTables!=null&&allTables.contains(tableName)){
			//setTableColumns(tableName);
		}else{
			List<String> tableList=commonMapper.getAllTables(para);
			cache.deleteCache("allUserTable");
			cache.putCache("allUserTable", tableList);
		}
	}
	@Override
	public String getTableColumn(String tableName, String fieldName, Class clazz) {
		HashMap<String, Map<String,Object>> tableMap = cache.getCache("heroTable", HashMap.class);
		if(tableMap!=null&&tableMap.containsKey(tableName)) {
			Map<String,Object> cols=tableMap.get(tableName);
			return cols.get(fieldName)==null?"":cols.get(fieldName).toString();
		}else {
			Map<String,Object> cols=getTableColumns(clazz);
			this.putHeroTableCols(cols, tableName);
			return cols.get(fieldName)==null?"":cols.get(fieldName).toString();
		}
	}
	public static Map<String, Object> getTableColumns(Class obj) {
		Field[] fields = obj.getDeclaredFields();
		Map<String, Object> fieldNames = new HashMap<String, Object>();
		for (int i = 0; i < fields.length; i++) {
			System.out.println(fields[i].getType());
			Field f = fields[i];
			Transient annotation = f.getAnnotation(Transient.class);
			// 有该类型的注解存在
			if (annotation != null) {
				continue;
			}
			Column cAnnotation = f.getAnnotation(Column.class);
			if (cAnnotation != null) {
				fieldNames.put(f.getName(), cAnnotation.name());
			} else {
				fieldNames.put(f.getName(), NameHandler.getColumnName(f.getName()));
			}
		}
		return fieldNames;
	}
	@Override
	public Map<String,Object> getHeroTableColumns(String tableName,Class obj) {
		
		HashMap<String, Map<String,Object>> tableMap = cache.getCache("heroTable", HashMap.class);
		
		if (tableMap!=null&&!tableMap.isEmpty()&&tableMap.containsKey(tableName)) {
			// System.out.println("存在表在缓存:"+tableName);
			return tableMap.get(tableName);
		} else {
			Map<String,Object> colMap=getTableColumns(obj);
			if (tableMap == null || tableMap.isEmpty()) {
				tableMap=new HashMap<String, Map<String,Object>>();	
			}
			tableMap.put(tableName, colMap);
			putHeroTableCols(colMap,tableName);
		}
		Map<String,Object> cols = tableMap.get(tableName);
		if (cols != null && !cols.isEmpty()) {
			return cols;
		} else {
			return new HashMap<String,Object>();
		}
	}
	
	public synchronized Map<String,Object>  putHeroTableCols(Map<String,Object> tableColumns,String tableName) {
		HashMap<String, Map<String,Object>> userTableMap = cache.getCache("heroTable", HashMap.class);
		if(userTableMap==null) {
			userTableMap=new HashMap<String, Map<String,Object>>();
		}
		userTableMap.remove(tableName);
		userTableMap.put(tableName, tableColumns);
		cache.deleteCache("heroTable");
		cache.putCache("heroTable", userTableMap);
		return tableColumns;
	}
	


	@PostConstruct
	@Override
	public void initAllTypeGroups() {
		String dataBaseType = sqlMapper.getDatabaseType();
		cache.deleteCache("dataBaseType");
		cache.putCache("dataBaseType", dataBaseType);
		getInitAllTypeGroups("");
	}
	@Override
	public void getInitAllTypeGroups(String typeGroupId) {
		System.out.println("执行SystemServiceImpl: initAllTypeGroups构造方法");
		Map para = new HashMap();
		para.put("typeGroupId", typeGroupId);
		List<Map> groupList = dictGroupTypeMapper.getDictGroupList(para);
		// redisCacheService.putListCache("allTypeGroups", typeGroups);
		Map groupMap = new HashMap();
		groupMap = cache.getCache("typegroup", HashMap.class);
		if (groupMap == null || groupMap.isEmpty()) {
			groupMap = new HashMap();
		}
		for (Map tsTypegroup : groupList) {
			// String
			// typegroupcode=tsTypegroup.get("TYPE_GROUP_CODE").toString().toLowerCase();
			// String
			// isComplex=tsTypegroup.get("IS_COMPLEX")==null?"":tsTypegroup.get("IS_COMPLEX").toString();
			String typegroupcode = tsTypegroup.get("typeGroupCode").toString().toLowerCase();
			String isComplex = tsTypegroup.get("isComplex") == null ? "" : tsTypegroup.get("isComplex").toString();
			Map typrGroup = new HashMap();
			typrGroup.put("typegroupname", tsTypegroup.get("typeGroupName"));
			typrGroup.put("typegroupcode", typegroupcode);
			typrGroup.put("isComplex", isComplex);
			groupMap.put(typegroupcode, typrGroup);
			cache.deleteCache(typegroupcode);
			String typegroupid = tsTypegroup.get("id").toString();
			Map parameter = new HashMap();
			parameter.put("typegroupid", typegroupid);
			List<Map<String, Object>> dictTypeList = dictGroupTypeMapper.getDictTypeList(parameter);
			List<Map<String, Object>> typeList = new ArrayList<Map<String, Object>>();
			if (dictTypeList != null && !dictTypeList.isEmpty()) {
				for (Map<String, Object> type : dictTypeList) {
					Map<String, Object> typeMap = new HashMap<String, Object>();
					if (type == null) {
						continue;
					}
					if (type != null && type.containsKey("typeCode")) {
						typeMap.put("typecode", type.get("typeCode"));
					}
					if (type != null && type.containsKey("typeName")) {
						typeMap.put("typename", type.get("typeName"));
					}
					if (type != null && type.containsKey("hasSub")) {
						typeMap.put("hasSub", type.get("hasSub"));
					}
					typeMap.put("id", type.get("id"));
					if (null != typeMap.get("hasSub") && "1".equals(typeMap.get("hasSub").toString())) {
						List<Map<String, Object>> childTypeList = new ArrayList<Map<String, Object>>();
						childTypeList = getChildType(childTypeList, typegroupid, type.get("id").toString());
						typeMap.put("child", childTypeList);
					}

					typeList.add(typeMap);
				}
			}
			if (typeList != null && !typeList.isEmpty()) {
				cache.putListCache(typegroupcode, typeList);
			}

		}
		cache.deleteCache("typegroup");
		cache.putCache("typegroup", groupMap);

	}

	public List<Map<String, Object>> getChildType(List<Map<String, Object>> typeList, String typegroupid,
			String typeId) {
		Map parameter = new HashMap();
		parameter.put("typegroupid", typegroupid);
		parameter.put("typeId", typeId);
		List<Map<String, Object>> dictTypeList = dictGroupTypeMapper.getDictTypeList(parameter);
		// List typeList=new ArrayList();
		for (Map type : dictTypeList) {
			Map typeMap = new HashMap();
			typeMap.put("typecode", type.get("typeCode"));
			typeMap.put("typename", type.get("typeName"));
			typeMap.put("hasSub", type.get("hasSub"));
			typeMap.put("id", type.get("id"));
			if (null != typeMap.get("hasSub") && "1".equals(typeMap.get("hasSub").toString())) {
				List<Map<String, Object>> childTypeList = new ArrayList<Map<String, Object>>();
				getChildType(childTypeList, typegroupid, type.get("id").toString());
				typeMap.put("child", childTypeList);
			}
			typeList.add(typeMap);
		}
		return typeList;
	}
	@Override
	public void refleshTypesCach(TSType type) {
		String typeGroupId = type.getTypeGroupId();
		getInitAllTypeGroups(typeGroupId);
	}
	@Override
	public void refleshTypeGroupCach(String typeGroupId) {
		String sql = "select g.type_group_code  from T_S_TYPEGROUP g ";
		if (typeGroupId == null || typeGroupId.trim().equals("")) {
			return;
		}
		sql = sql + " where 1=1 ";
		sql = sql + " and g.ID='" + typeGroupId + "'";
		Map para = new HashMap();
		para.put("sql", sql);
		List<Map<String, Object>> typeGroups = commonMapper.selectListBySql(para);
		for (Map tsTypegroup : typeGroups) {
			String typegroup = tsTypegroup.get("typeGroupCode") == null ? ""
					: tsTypegroup.get("typeGroupCode").toString();
			cache.deleteCache(typegroup.toLowerCase());
		}
		TSTypegroup typegroup = commonService.get(TSTypegroup.class, typeGroupId);
		if (typegroup == null || typegroup.getTypeGroupCode() == null) {
			return;
		}
		String typegroupStr = typegroup.getTypeGroupCode();
		cache.deleteCache(typegroupStr.toLowerCase());
		getInitAllTypeGroups(typeGroupId);
	}

	// ----------------------------------------------------------------
	// ----------------------------------------------------------------
	@Override
	public Set<String> getOperationCodesByRoleIdAndFunctionId(String roleId, String functionId) {

		Map para = new HashMap();
		para.put("roleId", roleId);
		para.put("functionId", functionId);
		List<String> opCodes = roleMapper.getOperationCodesByRoleIdAndFunctionId(para);
		Set<String> operationCodes = new HashSet<String>(opCodes);
		return operationCodes;
	}
	@Override
	public Set<String> getOperationCodesByUserIdAndFunctionId(String userId, String functionId) {
		Map para = new HashMap();
		para.put("userId", userId);
		para.put("functionId", functionId);
		List<String> opCodes = roleMapper.getOperationCodesByUserIdAndFunctionId(para);
		Set<String> operationCodes = new HashSet<String>(opCodes);
		return operationCodes;
	}
	@Override
	public String getFunctionIdByFunctionUrl(String functionUrl) {
		String funcId = "";
		List<TSFunction> tsFuncs = commonService.findByProperty(TSFunction.class, "functionUrl", functionUrl);
		for (TSFunction ru : tsFuncs) {
			funcId = ru.getId();
			break;
		}
		return funcId;
	}

	// ----------------------------------------------------------------
	// ----------------------------------------------------------------
	@Override
	public Long doDuplicateCheck(DuplicateCheckPage duplicateCheckPage) {
		Long num = null;

		if (StringUtils.isNotBlank(duplicateCheckPage.getRowObid())) {
			// [2].编辑页面校验
			String sql = "SELECT count(*) FROM " + duplicateCheckPage.getTableName() + " WHERE "
					+ NameHandler.getColumnName(duplicateCheckPage.getFieldName())
					+ " =#{fieldValue} and id != #{id}";
			// num = jdbcDao.getCountForJdbcParam(sql, new
			// Object[]{duplicateCheckPage.getFieldVlaue(),duplicateCheckPage.getRowObid()});
			Map para = new HashMap();
			para.put("fieldValue", duplicateCheckPage.getFieldVlaue());
			para.put("id", duplicateCheckPage.getRowObid());
			num = commonService.getCountForJdbc(sql, para);
		} else {
			// [1].添加页面校验
			String sql = "SELECT count(*) FROM " + duplicateCheckPage.getTableName() + " WHERE "
					+ NameHandler.getColumnName(duplicateCheckPage.getFieldName()) + " =#{fieldValue}";
			// num = jdbcDao.getCountForJdbcParam(sql, new
			// Object[]{duplicateCheckPage.getFieldVlaue()});
			Map para = new HashMap();
			para.put("fieldValue", duplicateCheckPage.getFieldVlaue());
			num = commonService.getCountForJdbc(sql, para);
		}
		return num;

	}

	@Override
	public Object uploadFile(UploadFile uploadFile) {
		Object object = uploadFile.getObject();
		if (uploadFile.getFileKey() != null) {
			commonService.updateEntitie(object);
		} else {
			try {
				uploadFile.getMultipartRequest().setCharacterEncoding("UTF-8");
				MultipartHttpServletRequest multipartRequest = uploadFile.getMultipartRequest();
				ReflectHelper reflectHelper = new ReflectHelper(uploadFile.getObject());
				String uploadbasepath = uploadFile.getBasePath();// 文件上传根目录
				if (uploadbasepath == null) {
					uploadbasepath = ResourceUtil.getConfigByName("uploadpath");
				}
				Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
				// 文件数据库保存路径
				String path = uploadbasepath + "/";// 文件保存在硬盘的相对路径
				String realPath = uploadFile.getMultipartRequest().getSession().getServletContext().getRealPath("/")
						+ "/" + path;// 文件的硬盘真实路径
				File file = new File(realPath);
				if (!file.exists()) {
					file.mkdirs();// 创建根目录
				}
				if (uploadFile.getCusPath() != null) {
					realPath += uploadFile.getCusPath() + "/";
					path += uploadFile.getCusPath() + "/";
					file = new File(realPath);
					if (!file.exists()) {
						file.mkdirs();// 创建文件自定义子目录
					}
				} else {
					realPath += DataUtils.getDataString(DataUtils.yyyyMMdd) + "/";
					path += DataUtils.getDataString(DataUtils.yyyyMMdd) + "/";
					file = new File(realPath);
					if (!file.exists()) {
						file.mkdir();// 创建文件时间子目录
					}
				}
				String entityName = uploadFile.getObject().getClass().getSimpleName();
				// 设置文件上传路径
				if (entityName.equals("TSTemplate")) {
					realPath = uploadFile.getMultipartRequest().getSession().getServletContext().getRealPath("/")
							+ ResourceUtil.getConfigByName("templatepath") + "/";
					path = ResourceUtil.getConfigByName("templatepath") + "/";
				} else if (entityName.equals("TSIcon")) {
					realPath = uploadFile.getMultipartRequest().getSession().getServletContext().getRealPath("/")
							+ uploadFile.getCusPath() + "/";
					path = uploadFile.getCusPath() + "/";
				}
				String fileName = "";
				String swfName = "";
				for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
					MultipartFile mf = entity.getValue();// 获取上传文件对象
					fileName = mf.getOriginalFilename();// 获取文件名
					swfName = PinyinUtil
							.getPinYinHeadChar(oConvertUtils.replaceBlank(FileUtils.getFilePrefix(fileName)));// 取文件名首字母作为SWF文件名
					String extend = FileUtils.getExtend(fileName);// 获取文件扩展名
					String myfilename = "";
					String noextfilename = "";// 不带扩展名
					if (uploadFile.isRename()) {

						noextfilename = DataUtils.getDataString(DataUtils.yyyymmddhhmmss) + StringUtil.random(8);// 自定义文件名称
						myfilename = noextfilename + "." + extend;// 自定义文件名称
					} else {
						myfilename = fileName;
					}

					String savePath = realPath + myfilename;// 文件保存全路径
					String fileprefixName = FileUtils.getFilePrefix(fileName);
					if (uploadFile.getTitleField() != null) {
						reflectHelper.setMethodValue(uploadFile.getTitleField(), fileprefixName);// 动态调用set方法给文件对象标题赋值
					}
					if (uploadFile.getExtend() != null) {
						// 动态调用 set方法给文件对象内容赋值
						reflectHelper.setMethodValue(uploadFile.getExtend(), extend);
					}
					if (uploadFile.getByteField() != null) {
						// 二进制文件保存在数据库中
						reflectHelper.setMethodValue(uploadFile.getByteField(),
								StreamUtils.InputStreamTOByte(mf.getInputStream()));
					}
					File savefile = new File(savePath);
					if (uploadFile.getRealPath() != null) {
						// 设置文件数据库的物理路径
						reflectHelper.setMethodValue(uploadFile.getRealPath(), path + myfilename);
					}
					commonService.save(object);
					// 文件拷贝到指定硬盘目录
					FileCopyUtils.copy(mf.getBytes(), savefile);
					if (uploadFile.getSwfpath() != null) {
						// 转SWF
						// reflectHelper.setMethodValue(uploadFile.getSwfpath(), path +
						// FileUtils.getFilePrefix(myfilename) + ".swf");
						// SwfToolsUtil.convert2SWF(savePath);
					}

				}
			} catch (Exception e1) {
			}
		}
		return object;
	}

	@Override
	public HttpServletResponse viewOrDownloadFile(UploadFile uploadFile) {
		uploadFile.getResponse().setContentType("UTF-8");
		uploadFile.getResponse().setCharacterEncoding("UTF-8");
		InputStream bis = null;
		BufferedOutputStream bos = null;
		HttpServletResponse response = uploadFile.getResponse();
		HttpServletRequest request = uploadFile.getRequest();
		String ctxPath = request.getSession().getServletContext().getRealPath("/");
		String downLoadPath = "";
		long fileLength = 0;
		if (uploadFile.getRealPath() != null && uploadFile.getContent() == null) {
			downLoadPath = ctxPath + uploadFile.getRealPath();
			fileLength = new File(downLoadPath).length();
			try {
				bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		} else {
			if (uploadFile.getContent() != null) {
				bis = new ByteArrayInputStream(uploadFile.getContent());
			}
			fileLength = uploadFile.getContent().length;
		}
		try {
			if (!uploadFile.isView() && uploadFile.getExtend() != null) {
				if (uploadFile.getExtend().equals("text")) {
					response.setContentType("text/plain;");
				} else if (uploadFile.getExtend().equals("doc")) {
					response.setContentType("application/msword;");
				} else if (uploadFile.getExtend().equals("xls")) {
					response.setContentType("application/ms-excel;");
				} else if (uploadFile.getExtend().equals("pdf")) {
					response.setContentType("application/pdf;");
				} else if (uploadFile.getExtend().equals("jpg") || uploadFile.getExtend().equals("jpeg")) {
					response.setContentType("image/jpeg;");
				} else {
					response.setContentType("application/x-msdownload;");
				}
				response.setHeader("Content-disposition",
						"attachment; filename=" + new String(
								(uploadFile.getTitleField() + "." + uploadFile.getExtend()).getBytes("GBK"),
								"ISO8859-1"));
				response.setHeader("Content-Length", String.valueOf(fileLength));
			}
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return response;
	}

	@Override
	public HttpServletResponse createXml(ImportFile importFile) {
		HttpServletResponse response = importFile.getResponse();
		HttpServletRequest request = importFile.getRequest();
		try {
			// 创建document对象
			Document document = DocumentHelper.createDocument();
			document.setXMLEncoding("UTF-8");
			// 创建根节点
			String rootname = importFile.getEntityName() + "s";
			Element rElement = document.addElement(rootname);
			Class entityClass = importFile.getEntityClass();
			String[] fields = importFile.getField().split(",");
			// 得到导出对象的集合
			// List objList = loadAll(entityClass);
			String tableName = NameHandler.getTableName(entityClass.getSimpleName());
			String sql = "select * from " + tableName;
			Map paras = new HashMap();
			List objList = commonService.findByQueryString(sql, entityClass, paras);
			Class classType = entityClass.getClass();
			for (Object t : objList) {
				Element childElement = rElement.addElement(importFile.getEntityName());
				for (int i = 0; i < fields.length; i++) {
					String fieldName = fields[i];
					// 第一为实体的主键
					if (i == 0) {
						childElement.addAttribute(fieldName, String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
					} else {
						Element name = childElement.addElement(fieldName);
						name.setText(String.valueOf(TagUtil.fieldNametoValues(fieldName, t)));
					}
				}

			}
			String ctxPath = request.getSession().getServletContext().getRealPath("");
			File fileWriter = new File(ctxPath + "/" + importFile.getFileName());
			XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(fileWriter));

			xmlWriter.write(document);
			xmlWriter.close();
			// 下载生成的XML文件
			UploadFile uploadFile = new UploadFile(request, response);
			uploadFile.setRealPath(importFile.getFileName());
			uploadFile.setTitleField(importFile.getFileName());
			uploadFile.setExtend("bak");
			viewOrDownloadFile(uploadFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	@Override
	public void parserXml(String fileName) {
		try {
			File inputXml = new File(fileName);
			Class entityClass;
			// 读取文件
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(inputXml);
			Element employees = document.getRootElement();
			// 遍历根节点下的子节点
			for (Iterator i = employees.elementIterator(); i.hasNext();) {
				Element employee = (Element) i.next();
				// 有实体名反射得到实体类
				entityClass = GenericsUtils.getEntityClass(employee.getName());
				// 得到实体属性
				Field[] fields = TagUtil.getFiled(entityClass);
				// 得到实体的ID
				String id = employee.attributeValue(fields[0].getName());
				String tableName = NameHandler.getTableName(entityClass.getSimpleName());
				// 判断实体是否已存在
				Object obj1 = commonService.getEntity(entityClass, id);
				// 实体不存在new个实体
				if (obj1 == null) {
					obj1 = entityClass.newInstance();
				}
				// 根据反射给实体属性赋值
				for (Iterator j = employee.elementIterator(); j.hasNext();) {
					Element node = (Element) j.next();
					for (int k = 0; k < fields.length; k++) {
						if (node.getName().equals(fields[k].getName())) {
							String fieldName = fields[k].getName();
							String stringLetter = fieldName.substring(0, 1).toUpperCase();
							String setName = "set" + stringLetter + fieldName.substring(1);
							Method setMethod = entityClass.getMethod(setName, new Class[] { fields[k].getType() });
							String type = TagUtil.getColumnType(fieldName, fields);
							if (type.equals("int")) {
								setMethod.invoke(obj1, new Integer(node.getText()));
							} else if (type.equals("string")) {
								setMethod.invoke(obj1, node.getText().toString());
							} else if (type.equals("short")) {
								setMethod.invoke(obj1, new Short(node.getText()));
							} else if (type.equals("double")) {
								setMethod.invoke(obj1, new Double(node.getText()));
							} else if (type.equals("Timestamp")) {
								setMethod.invoke(obj1, new Timestamp(
										DataUtils.str2Date(node.getText(), DataUtils.datetimeFormat).getTime()));
							}
						}
					}
				}
				if (obj1 != null) {
					commonService.update(obj1);
				} else {
					commonService.save(obj1);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 从session中获取用户对象，没有的话，用getUserName()获取用户对象存入session
	 * 
	 * @param req
	 *            request
	 * @param TSUser
	 *            当前登录账号
	 */
	@Override
	public TSUser getUserFromSeesion(TSUser user) {
		if (StringUtil.isEmpty(user.getUserName())) {
			return null;
		}
		user.setUserName(user.getUserName() == null ? "" : user.getUserName());
		user.setWxId(user.getWxId() == null ? "" : user.getWxId());
		Map<String, String> para = new HashMap();
		String sql = new SQL() {
			{
				SELECT("bu.*,u.*,d.DEPART_NAME");
				FROM("T_S_BASE_USER bu");

				INNER_JOIN("T_S_USER u on bu.ID=u.ID and bu.STATUS='1'");
				INNER_JOIN("T_S_DEPART d on d.ID=bu.DEPART_ID");
				WHERE("(bu.USER_NAME=#{username} or u.MOBILE_PHONE=#{username} or WX_ID=#{wxId})");
			}
		}.toString();
		para.put("sql", sql);
		para.put("username", user.getUserName());
		List<TSUser> users = userMapper.selectListBySql(para);
		if (users != null && users.size() > 0) {
			return users.get(0);
		}
		return null;
	}

	public static void main(String[] args) {
		Map beanMap = new HashMap();
		beanMap.put("id", "1");
		beanMap.put("vipId", "5");
		beanMap.put("userName", "userName");
		beanMap.put("departId", "departId5");
		DozerBeanMapper dozer = new DozerBeanMapper();
		TSUser user = dozer.map(beanMap, TSUser.class);
	}

	

	
}
